package cn.edu.hbwe.book.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

import cn.edu.hbwe.book.entity.Book;
import cn.edu.hbwe.book.entity.OrderItem;
import cn.edu.hbwe.book.entity.Orders;
import cn.edu.hbwe.book.utils.C3P0Util;

public class OrderItemDao {
	private static QueryRunner run = new QueryRunner(C3P0Util.getDataSource());

	// 添加订单项
	public void addOrderItem(Orders order) throws SQLException {
		// 生成sql语句
		String sql = "insert into orderItem values(?,?,?)";
		List<OrderItem> items = order.getOrderItems();

		Object[][] params = new Object[items.size()][3];

		for (int i = 0; i < params.length; i++) {
			params[i][0] = items.get(i).getOrder().getId();
			params[i][1] = items.get(i).getBook().getId();
			params[i][2] = items.get(i).getBuyNum();
		}

		run.batch(sql, params);
	}

	// 根据订单查找订单项.并将订单项中商品查找到。
	public List<OrderItem> findOrderItemByOrder(final Orders order) throws SQLException {
		String sql = "select * from orderItem,Products where products.id=orderItem.product_id and order_id=?";

		return run.query(sql, new ResultSetHandler<List<OrderItem>>() {
			public List<OrderItem> handle(ResultSet rs) throws SQLException {

				List<OrderItem> items = new ArrayList<OrderItem>();
				while (rs.next()) {
					OrderItem item = new OrderItem();

					item.setOrder(order);
					item.setBuyNum(rs.getInt("buynum"));

					Book b = new Book();
					b.setCategory(rs.getString("category"));
					b.setId(rs.getString("id"));
					b.setDescription(rs.getString("description"));
					b.setImgurl(rs.getString("imgurl"));
					b.setName(rs.getString("name"));
					b.setPnum(rs.getInt("pnum"));
					b.setPrice(rs.getDouble("price"));
					item.setBook(b);

					items.add(item);
				}

				return items;
			}
		}, order.getId());
	}

	// 根据订单id删除订单项
	public void delOrderItems(String id) throws SQLException {
		String sql = "delete from orderItem where order_id=?";
		run.update(sql, id);
	}

}
